from flask import Blueprint, request, jsonify, current_app
from app.extensions import db
from app.models.post import Post
from app.models.post_image import PostImage
from app.models.categories import Category
from app.models.user import User  # 添加用户模型导入
from app.routes.auth import token_required
from datetime import datetime
import os
from werkzeug.utils import secure_filename
from sqlalchemy.orm import joinedload


post_bp = Blueprint('post', __name__)

# 允许的图片扩展名
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'webp'}

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def save_post_image(file, post_id, order):
    """保存帖子图片并返回URL"""
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        # 生成唯一文件名：post_{post_id}_{timestamp}_{order}_{filename}
        timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
        unique_filename = f"post_{post_id}_{timestamp}_{order}_{filename}"
        
        # 保存路径
        upload_folder = current_app.config.get('UPLOAD_FOLDER', 'static/uploads/posts')
        os.makedirs(upload_folder, exist_ok=True)
        file_path = os.path.join(upload_folder, unique_filename)
        file.save(file_path)
        
        # 返回相对URL路径
        return f"/{upload_folder}/{unique_filename}"
    return None

@post_bp.route('/api/dynamics', methods=['POST'])
@token_required
def create_post(current_user):
    """发布动态接口 - 使用现有的Post表"""
    try:
        # 获取表单数据
        content = request.form.get('content')
        record_type = request.form.get('recordType')
        category_id = request.form.get('categoryId')
        amount = request.form.get('amount')
        record_date_str = request.form.get('recordDate')
        
        # 参数验证
        if not all([content, record_type, category_id, amount, record_date_str]):
            return jsonify({
                'success': False, 
                'message': '缺少必填参数'
            }), 400
        
        # 验证分类是否存在
        category = Category.query.get(category_id)
        if not category:
            return jsonify({
                'success': False, 
                'message': '分类不存在'
            }), 404
        
        # 解析日期
        try:
            record_date = datetime.fromisoformat(record_date_str.replace('Z', '+00:00'))
        except ValueError:
            return jsonify({
                'success': False, 
                'message': '日期格式错误'
            }), 400
        
        # 创建帖子记录（使用现有的Post表）
        post = Post(
            user_id=current_user.user_id,
            content=content,
            post_time=datetime.utcnow(),  # 使用现有字段
            # 新增的收支字段
            record_type=record_type,
            category_id=category_id,
            amount=amount,
            record_date=record_date,
            is_delete=False  # 确保设置为未删除
        )
        
        db.session.add(post)
        db.session.flush()  # 获取post_id但不提交事务
        
        # 处理图片上传（使用现有的PostImage表）
        image_urls = []
        if 'images' in request.files:
            images = request.files.getlist('images')
            for i, image_file in enumerate(images):
                if image_file and image_file.filename:
                    image_url = save_post_image(image_file, post.post_id, i)
                    if image_url:
                        # 创建图片记录（使用现有的PostImage表）
                        post_image = PostImage(
                            post_id=post.post_id,
                            image_url=image_url,
                            sort_order=i
                        )
                        db.session.add(post_image)
                        image_urls.append(image_url)
        
        # 提交所有更改
        db.session.commit()
        
        # 构建响应数据
        response_data = {
            'dynamicId': str(post.post_id),  # 使用post_id作为dynamicId
            'content': content,
            'images': image_urls,
            'createdAt': post.post_time.isoformat() + 'Z'  # 使用post_time作为createdAt
        }
        
        return jsonify({
            'success': True,
            'data': response_data,
            'message': '动态发布成功'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False, 
            'message': f'发布动态失败: {str(e)}'
        }), 500

@post_bp.route('/api/dynamics', methods=['GET'])
@token_required
def get_posts(current_user):
    """获取动态列表接口"""
    try:
        # 获取当前用户的所有正常帖子（未删除）
        posts = Post.query.filter_by(
            user_id=current_user.user_id,
            is_delete=False
        ).order_by(Post.post_time.desc()).all()
        
        result = []
        for post in posts:
            # 获取帖子的图片
            image_urls = [img.image_url for img in post.images]
            
            # 构建动态信息
            post_info = {
                'id': post.post_id,
                'content': post.content,
                'recordType': post.record_type,
                'categoryId': post.category_id,
                'categoryName': post.category.name if post.category else '未知分类',
                'amount': float(post.amount),
                'recordDate': post.record_date.isoformat() + 'Z',
                'images': image_urls,
                'likeCount': post.like_count,
                'createdAt': post.post_time.isoformat() + 'Z'
            }
            result.append(post_info)
        
        return jsonify({
            'success': True,
            'data': {
                'dynamics': result
            }
        })
        
    except Exception as e:
        return jsonify({
            'success': False, 
            'message': f'获取动态失败: {str(e)}'
        }), 500

# 新增接口实现

@post_bp.route('/api/posts/list', methods=['GET'])
@token_required
def get_posts_list(current_user):
    """获取动态所有帖子列表接口（分页）"""
    try:
        page = int(request.args.get('page', 1))
        page_size = int(request.args.get('page_size', 5))
        
        # 计算分页
        offset = (page - 1) * page_size
        
        # 查询帖子总数（只查询未删除的帖子）
        total = Post.query.filter_by(is_delete=False).count()
        
        # 查询帖子列表（按发布时间倒序，只查询未删除的帖子）
        posts = Post.query \
            .filter_by(is_delete=False) \
            .join(User, Post.user_id == User.user_id) \
            .options(joinedload(Post.user), joinedload(Post.images), joinedload(Post.category)) \
            .order_by(Post.post_time.desc()) \
            .offset(offset) \
            .limit(page_size) \
            .all()
        
        posts_data = []
        for post in posts:
            post_data = {
                'post_id': post.post_id,
                'user_id': post.user_id,
                'user_nickname': post.user.nickname if post.user else '未知用户',
                'user_avatar': post.user.avatar_url or '/static/avatars/default_avatar.jpg',
                'content': post.content,
                'like_count': post.like_count,
                'post_time': post.post_time.strftime('%Y-%m-%d %H:%M:%S'),
                'record_type': post.record_type,
                'category_id': post.category_id,
                'category_name': post.category.name if post.category else '未知分类',
                'amount': float(post.amount),
                'record_date': post.record_date.strftime('%Y-%m-%d %H:%M:%S'),
                'images': []
            }
            
            # 添加图片信息
            for image in post.images:
                post_data['images'].append({
                    'image_id': image.image_id,
                    'image_url': image.image_url,
                    'sort_order': image.sort_order
                })
            
            posts_data.append(post_data)
        
        return jsonify({
            'code': 200,
            'msg': '成功',
            'data': {
                'total': total,
                'list': posts_data
            }
        })
        
    except Exception as e:
        return jsonify({
            'code': 500,
            'msg': f'获取动态列表失败: {str(e)}'
        }), 500

@post_bp.route('/api/posts/like', methods=['POST'])
@token_required
def like_post(current_user):
    """动态点赞接口"""
    try:
        data = request.get_json()
        post_id = data.get('post_id')
        
        if not post_id:
            return jsonify({
                'code': 400,
                'msg': '帖子ID不能为空'
            }), 400
        
        # 查询帖子
        post = Post.query.filter_by(post_id=post_id, is_delete=False).first()
        if not post:
            return jsonify({
                'code': 404,
                'msg': '帖子不存在'
            }), 404
        
        # 直接更新点赞数
        post.like_count += 1
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'msg': '点赞成功',
            'data': {
                'new_like_count': post.like_count
            }
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'msg': f'点赞失败: {str(e)}'
        }), 500

@post_bp.route('/api/posts/my', methods=['GET'])
@token_required
def get_my_posts(current_user):
    """获取当前用户的所有帖子接口"""
    try:
        page = int(request.args.get('page', 1))
        page_size = int(request.args.get('page_size', 5))
        
        offset = (page - 1) * page_size
        
        # 查询当前用户的帖子总数（只查询未删除的）
        total = Post.query.filter_by(
            user_id=current_user.user_id, 
            is_delete=False
        ).count()
        
        # 查询当前用户的帖子
        posts = Post.query \
            .filter_by(user_id=current_user.user_id, is_delete=False) \
            .options(joinedload(Post.user), joinedload(Post.images), joinedload(Post.category)) \
            .order_by(Post.post_time.desc()) \
            .offset(offset) \
            .limit(page_size) \
            .all()
        
        posts_data = []
        for post in posts:
            post_data = {
                'post_id': post.post_id,
                'user_id': post.user_id,
                'user_nickname': post.user.nickname if post.user else '未知用户',
                'user_avatar': post.user.avatar_url or '/static/avatars/default_avatar.jpg',
                'content': post.content,
                'like_count': post.like_count,
                'post_time': post.post_time.strftime('%Y-%m-%d %H:%M:%S'),
                'record_type': post.record_type,
                'category_id': post.category_id,
                'category_name': post.category.name if post.category else '未知分类',
                'amount': float(post.amount),
                'record_date': post.record_date.strftime('%Y-%m-%d %H:%M:%S'),
                'images': []
            }
            
            for image in post.images:
                post_data['images'].append({
                    'image_id': image.image_id,
                    'image_url': image.image_url,
                    'sort_order': image.sort_order
                })
            
            posts_data.append(post_data)
        
        return jsonify({
            'code': 200,
            'msg': '成功',
            'data': {
                'total': total,
                'list': posts_data
            }
        })
        
    except Exception as e:
        return jsonify({
            'code': 500,
            'msg': f'获取我的帖子失败: {str(e)}'
        }), 500

@post_bp.route('/api/posts/delete', methods=['DELETE'])
@token_required
def delete_post(current_user):
    """删除个人帖子接口"""
    try:
        data = request.get_json()
        post_id = data.get('post_id')
        
        if not post_id:
            return jsonify({
                'code': 400,
                'msg': '帖子ID不能为空'
            }), 400
        
        # 查询帖子
        post = Post.query.filter_by(post_id=post_id).first()
        if not post:
            return jsonify({
                'code': 404,
                'msg': '帖子不存在'
            }), 404
        
        # 检查权限：只能删除自己的帖子
        if post.user_id != current_user.user_id:
            return jsonify({
                'code': 403,
                'msg': '无权删除他人帖子'
            }), 403
        
        # 软删除：设置is_delete为True
        post.is_delete = True
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'msg': '删除成功',
            'data': None
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'msg': f'删除失败: {str(e)}'
        }), 500
